package com.coco.seck.mqqueue;

import com.coco.common.constant.Constant;
import com.coco.seck.mapper.SeckillOrderMapper;
import com.coco.seck.pojo.TbSeckillOrder;
import lombok.extern.slf4j.Slf4j;
import org.checkerframework.checker.units.qual.A;
import org.springframework.amqp.core.Message;
import org.springframework.amqp.rabbit.annotation.RabbitListener;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Component;

import java.io.UnsupportedEncodingException;
import java.util.Date;
import java.util.Map;

/**
 * @author HanSama
 * @date 2021年08月08日 19:10
 */
@Component
@Slf4j
public class DelayedQueueConsumer {

    @Autowired
    private SeckillOrderMapper seckillOrderMapper;

    @Autowired
    private RedisTemplate redisTemplate;

    public static final String DELAYED_QUEUE_NAME = "delayed.queue";

    // 接收延迟消息
    @RabbitListener(queues = DELAYED_QUEUE_NAME)
    public void  receiveDelayedQueue(Message message){
       String msg = new String(message.getBody());

        log.info("当前时间：{},收到延时队列的消息：{}", new Date().toString(), msg);

        long id = Long.parseLong(msg);
        TbSeckillOrder seckillOrder = seckillOrderMapper.findOneById(id);

        //判断账单是否被支付
        if (!seckillOrder.getStatus().equals(Constant.OrderStatus.STATUS_TWO)){
            //  修改订单状态
            seckillOrderMapper.updateStatus(id, Constant.OrderStatus.STATUS_THREE);

            //redis秒杀商品数量回退
            redisTemplate.opsForValue().increment(Constant.RedisKeyConstant.GOODS_KEY_TEMPLATE+seckillOrder.getSeckillId());
            //从秒杀名单中去除该用户
            Map entries = redisTemplate.opsForHash().entries(Constant.RedisKeyConstant.GOODS_NUM_TEMPLATE+seckillOrder.getSeckillId());
            Integer num = (Integer) entries.get(Constant.RedisKeyConstant.USER_TEMPLATE + seckillOrder.getUserId());
            entries.put(Constant.RedisKeyConstant.USER_TEMPLATE+seckillOrder.getUserId(),num-1);
            redisTemplate.opsForHash().putAll(Constant.RedisKeyConstant.GOODS_NUM_TEMPLATE+seckillOrder.getSeckillId(),entries);
        }

    }
}
